//Make sure that the JSON Library is loaded

/**
 * The Footbar global namespace
 * @class Trucoder.SearchService
 * @static
 */
if (typeof Trucoder == "undefined") {
    Trucoder = {};
}
Trucoder.SearchService={
/**
 * Hold Information about last search
 */
    lastSearchMethod:{},
    searchResults:[],
    gIsSearchPreloaded:false,
    gStartRecordIndex:1,
    gEndRecordIndex:10,
    gCurrentPageIndex:1,

    totalPages:0,
    gLastSearchXMLData:null,

/**
 * Indicate if panel is loaded
 */
    isLoaded:false,

    init:function(){
        dump("\nIniting Trucoder.SearchService = "+this.isLoaded );
        Footbar.Plugins.init ();
        this.isLoaded = true;
    },

/**
 * Register tabs so they will become clicable
 */
    registerTabs__REMOVEME:function(){
        dump("\n Tabs registered");

        //Bind the RSSConfig to save data on blur
        var CustomTab_RSSConfig = {
            index:3,
            preventDefault:true,
            panelName:'CustomTab_RSSConfig',
            onClick:function(e){
                dump("\n > ***************** onClick "+e.currentTarget.tagName);
                dump("\n       >  isSelected = "+e.currentTarget.getAttribute('selected'));

            },
            onBlur:function(e){
                var elem=e.target;
                dump("\n >onBlur "+e.currentTarget.tagName);
                /*
                while(elem.parentNode.id!='trucoder-panels-srv-tabs'){
                    dump("\n >> "+e.type )
                    for(x in e){
                        //dump("\n       - "+x)
                    }
                    elem=elem.parentNode;
                }
                */
            }
        }
        Footbar.TabWatcher.bindSingleTab('trucoder-panels-srv-tabs', CustomTab_RSSConfig);

        Footbar.TabWatcher.initalize();
    },

/**
 * Get Numbr of records per page from properties
 */
    gRecordsPerPage:function() {
        /*
        if (nsPreferences.copyUnicharPref("trucoder.plugin.records_per_page") == null) {
            return 10;
        } else {
            return parseInt(nsPreferences.copyUnicharPref("trucoder.plugin.records_per_page"));
        } */
        return 10;
    },
/**
 * Reset values before next search
 */
    reset:function(){
        this.searchResults=[];
        this.gIsSearchPreloaded=false;
        this.gStartRecordIndex=1;
        this.gEndRecordIndex=this.gRecordsPerPage();
        this.gCurrentPageIndex=1;
    },


/**
 * data Object containing keywords selected and searchType
 */
    doSearchKeywords:function (data){
        dump("\n 1.doSearchKeywords="+data);
        data =  JSON.parse(data)
        this.reset();
        this.lastSearchMethod={
            method:'keyword',
            data:data.keywords,
            type:data.searchType
        }
        this.parseXMLSearchResults( Footbar.Plugins.getActiveEngine().searchByKeywords( data.keywords, data.searchType ), false );
    },
/**
 *
 * @param {Object||String} xmlObject Accespts XMLDocument or String
 */
    parseXMLSearchResults:function(xmlObject, cacheXML){
        var xmldata = null;
        var searchContainer=document.getElementById('footbar-search-container');
        searchContainer.style.visibility="visible";
        if(xmlObject){
            if(typeof(xmlObject)=='string'){
                xmldata = (new DOMParser()).parseFromString(xmlObject, "text/xml");
            }else{
                xmldata=xmlObject;
            }
        }else{
            xmldata=gLastSearchXMLData;
        }

        var gridList=document.getElementById( 'search-list-tree' );
        var	treechildren = gridList.getElementsByTagName("treechildren")[0];

        //Suppres Events
        Footbar.TreeUtil.suppresEvents( gridList.view.selection );
        //Prepare the tree : delete all the node from the treechildren
        var rootElements=treechildren;//tree.getElementsByTagName("treechildren")[0];
        try {
            while (rootElements.firstChild){
                rootElements.removeChild(rootElements.firstChild);
            };
        } catch(e) {
            alert(e)
        }
        //Restore suppresed events
        Footbar.TreeUtil.restoreSuppresedEvents();

        if(!this.gIsSearchPreloaded){
            this.preloadSearchItems(xmldata);
        }

        var root = xmldata.getElementsByTagName("root")[0];
        var items = root.getElementsByTagName("row");

        var reminder=0;
        this.totalPages=Math.round((items.length)/this.gRecordsPerPage());//-(items.length%gRecordsPerPage))
        this.gStartRecordIndex=(this.gCurrentPageIndex*this.gRecordsPerPage())-this.gRecordsPerPage();
        this.gEndRecordIndex=this.gCurrentPageIndex*this.gRecordsPerPage()
        if((items.length%this.gRecordsPerPage())>0){
            this.totalPages++;
        }

        var resultsetLabel=document.getElementById('footbar-resultset-label');

        if(resultsetLabel){
            var labelValue="Page {currentPage} of {totalPages}";
            labelValue=labelValue.replace("{currentPage}", this.gCurrentPageIndex);
            labelValue=labelValue.replace("{totalPages}", this.totalPages);
            resultsetLabel.value=labelValue

        }

        var elementPrevious=document.getElementById('footbar-resultset-previous-button');
        if(this.gCurrentPageIndex>1){
            elementPrevious.setAttribute("disabled", false);
        }else{
            elementPrevious.setAttribute("disabled", true);
        }

        var elementNext=document.getElementById('footbar-resultset-next-button');
        if(this.gCurrentPageIndex<this.totalPages){
            elementNext.setAttribute("disabled", false);
        }else{
            elementNext.setAttribute("disabled", true);
        }

        //alert("gStartRecordIndex="+gStartRecordIndex+"\n"+"gEndRecordIndex="+gEndRecordIndex);

        //for (var i=0;i<items.length;i++){
        for (var i=this.gStartRecordIndex;i<this.gEndRecordIndex;i++){
            var itemrow=items[i];
            if(itemrow==null){
                break;
            }

            var realIndex=this.gStartRecordIndex+i;
            var title=itemrow.getElementsByTagName("title")[0];
            var keywords=itemrow.getElementsByTagName("keywords")[0];
            var description=itemrow.getElementsByTagName("description")[0];
            var code=itemrow.getElementsByTagName("code")[0];
            var	treeitem = document.createElement("treeitem");
            var	treerow = document.createElement("treerow");
            treerow.setAttribute("id",  "search-treerow-"+i);
            var label_title= document.createElement("treecell");
            label_title.setAttribute("label",  i+" : "+title.textContent);

            //Process keywords
            var keywordsLabel="";
            var kdelim=",";
            var keywordData=[];
            var keywordList=itemrow.getElementsByTagName("pair");
            for(var k=0;k<keywordList.length;k++){
                if(keywordList.length-1==k)kdelim="";
                keywordsLabel+=keywordList[k].getAttribute("value")+kdelim;
            }

            var label_kwid= document.createElement("treecell");
            label_kwid.setAttribute("label", keywordsLabel );

            var readFlag="unread";
            if(this.searchResults[i].read){
                readFlag = "read";
            }else{
                readFlag = "unread";
            }
            label_title.setAttribute("properties", readFlag);
            label_kwid.setAttribute("properties", readFlag);

            treerow.appendChild(label_title);
            treerow.appendChild(label_kwid);

            treerow.setAttribute("id", "footbar-search-list-"+i);
            treeitem.appendChild(treerow);

            treechildren.appendChild(treeitem);
        }

        //Determine the XY possition of the mouse
        var searchGridXYCallback=function(e){
            var event=e;
            var posx=gridList.boxObject.screenX;
            var posy=gridList.boxObject.y ;
            posx +=  e.clientX;
            posy =  e.clientY+posy/2;
            if(e.button==2){
                document.getElementById('clipmenu-searchresults').showPopup(document.documentElement, posx, posy, "bottomleft", "topleft");
            }
        }
        gridList.addEventListener("mousedown", searchGridXYCallback, false);

        //So we dont have to requery
        this.gLastSearchXMLData=xmldata;
    },
/**
 * Preload the search into an arraySo we don't have to parse the file all the time
 */
    preloadSearchItems:function(xmldata){
        var root = xmldata.getElementsByTagName("root")[0];
        var items = root.getElementsByTagName("row");

        for (var i=0;i<items.length;i++){
            var itemrow=items[i];
            var title=itemrow.getElementsByTagName("title")[0];
            var keywords=itemrow.getElementsByTagName("keywords")[0];
            var description=itemrow.getElementsByTagName("description")[0];
            var code=itemrow.getElementsByTagName("code")[0];

            //Process keywords
            var keywordsLabel="";
            var kdelim=",";
            var keywordData=[];
            var keywordList=itemrow.getElementsByTagName("pair");
            for(var k=0;k<keywordList.length;k++){
                if(keywordList.length-1==k)kdelim="";
                keywordsLabel+=keywordList[k].getAttribute("value")+kdelim;
                keywordData[keywordData.length]={
                    value:keywordList[k].getAttribute("value"),
                    key:keywordList[k].getAttribute("key")
                }
            }
            var obj=new Object();
            obj={
                title:title.textContent,
                keywords:{label:keywordsLabel,data:keywordData},
                description:description.textContent,
                code:code.textContent,
                language:code.getAttribute("language"),
                read:false,
                uid:itemrow.getAttribute("uid")
            };
            this.searchResults[this.searchResults.length]=obj;

            if(!this.searchResults[this.searchResults.length]){
                //	alert("Initalization error :searchResults[searchResults.length]"+searchResults.length)
            }
        }
        this.gIsSearchPreloaded=true;
        //alert("data preloaded="+searchResults.length);
    },

    searchTreeSelected:function(lang){
        var tree = document.getElementById('search-list-tree');
        var tabViewState=document.getElementById('footbar-tabView').checked;

        if(tree.currentIndex==-1){
            return ;
        }

        var treeIndex=(this.gCurrentPageIndex*this.gRecordsPerPage)-this.gRecordsPerPage+tree.currentIndex;

        var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                .getService(Components.interfaces.nsIWindowMediator);
        var browserWindow = wm.getMostRecentWindow("navigator:browser");
        var tabDocument = browserWindow.content.document;
        var unsafeWindow=browserWindow.content.window.wrappedJSObject;
        var tabDOM={document:tabDocument,window:unsafeWindow};

        alert(this.searchResults)
        if(lang==null){
            lang=this.searchResults[treeIndex].language+":nogutter:nocontrols";
        }else{
            lang=lang+":nogutter:nocontrols";
        }
        //mark the current row as read
        var selection = tree.contentView.getItemAtIndex(tree.currentIndex);
        var cells=selection.getElementsByTagName('treecell');
        for(var k=0;k<cells.length;k++){
            cells[k].setAttribute("properties","read");
        }

        //selection.firstChild.firstChild.setAttribute("properties","read");
        this.searchResults[treeIndex].read=true;
        var colorizeCode=function(object, showHeader){
            try{
                object.document.getElementById('footbar-code').value=this.searchResults[treeIndex].code;
                object.document.getElementById('footbar-code').className=lang;

                if(showHeader){
                    object.document.getElementById('trucoder-header').style.display="";
                    object.document.getElementById('trucoder-header-title').innerHTML=this.searchResults[treeIndex].title;
                    object.document.getElementById('trucoder-header-description').innerHTML=this.searchResults[treeIndex].description;

                }else{
                    object.document.getElementById('trucoder-header').style.display="none";
                }

                object.window.colorize();
            }catch(e){
                //alert(e);
            }
        }
        if(tabViewState){
            //Ref: http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Getting_access_to_the_Browser
            var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                    .getInterface(Components.interfaces.nsIWebNavigation)
                    .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                    .rootTreeItem
                    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                    .getInterface(Components.interfaces.nsIDOMWindow);


            var gBrowser=mainWindow.getBrowser();

            var num = gBrowser.browsers.length;
            var found=false;
            for (var i = 0; i < num; i++) {
                var b = gBrowser.getBrowserAtIndex(i);
                try {
                    if(b.currentURI.spec==tabURI){
                        gBrowser.selectedTab = b;
                        b.focus();
                        gBrowser.mTabContainer.selectedIndex=i;
                        // Focus *this* browser
                        gBrowser.focus();
                        found=true;
                        break;
                    }
                } catch(e) {
                    alert(e);
                }
            }

            colorizeCode(tabDOM, true);

        }else{
            colorizeCode(new codeFrame(0), false);
            colorizeCode(new codeFrame(1), false);
        }

        //Set the Decsription
        document.getElementById('footbar-iDescription').value=this.searchResults[treeIndex].description;
        document.getElementById('footbar-iDescription-split').value=this.searchResults[treeIndex].description;

    } ,

    observeXXXX: function (aSubject, aTopic, aData) {
        dump("\n Called New Observer ");
        //Make sure that the sidebar is open
        toggleSidebar('viewEmptySidebar', true);
        var msg=""
        msg+="\naSubject="+aSubject;
        msg+="\naTopic="+aTopic;
        msg+="\naData="+aData;
        msg+="\nself="+self;

        try{
            //
            //Trucoder.SearchService
            //This quarantees us that the object are loaded before they are called from withind sidebar- simple polling system
            //Need Better way of doing this
            var sidebarWindow = document.getElementById("sidebar").contentWindow;
            var iCheckForExistence=0
            iCheckForExistence=setInterval (function(){
                //wait for it to be completaly loaded
                if(sidebarWindow  && sidebarWindow.Trucoder  && sidebarWindow.Trucoder.SearchService.isLoaded){
                    dump("\nfound target window =" + iCheckForExistence)
                    clearInterval(iCheckForExistence);
                    doSearchKeywords( aData );
                }
                sidebarWindow = document.getElementById("sidebar").contentWindow;
            },50)

        }catch(e){
            alert(e);
        }

    },

    /**
     * @todo :
     */
    registerSearchObserver:function(){
        return;
        var self=this;
        var tcSearchObserver = {
            observe: function (aSubject, aTopic, aData) {
                //Make sure that the sidebar is open
                toggleSidebar('viewEmptySidebar', true);

                var msg=""
                msg+="\naSubject="+aSubject;
                msg+="\naTopic="+aTopic;
                msg+="\naData="+aData;
                msg+="\nself="+self;

                try{
                    //
                    //Trucoder.SearchService
                    //This quarantees us that the object are loaded before they are called from withind sidebar- simple polling system
                    //Need Better way of doing this
                    var sidebarWindow = document.getElementById("sidebar").contentWindow;
                    var iCheckForExistence=0
                    iCheckForExistence=setInterval (function(){
                        //wait for it to be completaly loaded
                        if(sidebarWindow  && sidebarWindow.Trucoder  && sidebarWindow.Trucoder.SearchService.isLoaded){
                            dump("\nfound target window =" + iCheckForExistence)
                            clearInterval(iCheckForExistence);
                            var event =  document.createEvent("trucoder-search-request-event");
                            event.initEvent( "type", false, false )
                            document.dispatchEvent (event);
                        }
                        sidebarWindow = document.getElementById("sidebar").contentWindow;
                    },50)

                }catch(e){
                    alert(e);
                }

            }
        };

        var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService);
        //Need to make sure that there is only one objserver registered
        var registeredObservers = observerService.enumerateObservers("trucoder-search-request");
        if(registeredObservers.hasMoreElements()){
            observerService.removeObserver(tcSearchObserver, "trucoder-search-request");
        } else{
            //Reregister Observer
            observerService.addObserver(tcSearchObserver, "trucoder-search-request", false);
        }
        dump("\n SearchService.registerSearchObserver ")
    }
}
//window.addEventListener ("load",Trucoder.SearchService.init , true)
